<?php

namespace app\queue\redis\push;

use app\exception\ApiException;
use app\extensions\lib\FcmAccessToken;
use app\extensions\lib\push\AndroidPush;
use app\extensions\lib\push\HmsPush;
use app\extensions\lib\push\IosPush;
use app\model\TokenInfo;
use support\Db;
use support\Log;
use support\Redis;
use Webman\RedisQueue\Consumer;

class Push implements Consumer
{
    // 要消费的队列名
    public $queue = 'push_queue';

    public static $update_redis_queue_key = 'push_queue';
    public $connection = 'default';



    public static function cacheProgressKey($request_id){
        return 'request_id_in_progress_'.$request_id;
    }

    public static function progressRecord($request_id,$time=5){
        $cacheKey = self::cacheProgressKey($request_id);
        Redis::set($cacheKey,time());
        $time && Redis::expire($cacheKey,$time);
    }


    // 消费
    public function consume($data)
    {
        $is_finish = $data['is_finish'] ?? false;
        $channel = $data['channel'] ?? '';
        $request_id = $data['request_id'] ?? '';//定义全局request_id
        //dump($data);
        if($is_finish){
            \app\extensions\lib\push\Push::finishRequestPush($request_id,$data['cate_id']??0,$channel);
            return;
        }
        $os_id = $data['os_id'] ?? 0;
        $item = $data['item'] ?? [];

        $page = $item['page'] ?? 1;
        $limit = $item['limit'] ?? 0;
        $message = $data['message'] ?? [];
        $chunkInfo = $data['chunkInfo'] ?? '';
        //dump($os_id.':Push:consume:'.count(explode(',',$item['tokens'])));
        if(!$message) return;
        //$result = [];
        $log = 'os_id:'.$os_id.':request_id:'.$request_id.':'."#$chunkInfo:#{$page}:{$limit}";
        try{

            if($os_id==3){
                $result = HmsPush::push($item,$message,$request_id);
            }elseif($os_id==2){
                $result = IosPush::push($item,$message,$request_id);
            }else{
                $result = AndroidPush::push($item,$message,$request_id);
            }
            Log::channel('push')->info($log.json_encode($result));
        }catch (ApiException $apiException){
            Log::channel('push')->warning($log.':'.$apiException->getMessage());
        }catch (\Throwable $exception){
            Log::channel('push')->error($log.':'.$exception->getMessage());
        }

    }
}